package cmd_server

import (
	"gitee.com/theegg/go-brick/app/boot"
	"gitee.com/theegg/go-brick/app/middleware"
	"gitee.com/theegg/go-brick/app/service/help/cvalidator"
	"gitee.com/theegg/go-brick/routers"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"github.com/spf13/cobra"
	"os"
)

var (
	dir string
)

var StartCmd = &cobra.Command{
	Use:          "server",
	Short:        "启动服务器",
	Example:      "go-brick server -dir /data/www/go-brick",
	SilenceUsage: true,
	RunE: func(cmd *cobra.Command, args []string) error {
		return run()
	},
}

func init() {
	StartCmd.PersistentFlags().StringVarP(&dir, "dir", "d", "", "启动服务，指定根目录,配置文件和storage在此目录")
}

func run() error {
	errBoot := boot.InitApp(dir)

	if errBoot != nil {
		panic(errBoot.Error())
		os.Exit(0)
	}

	router := gin.Default()

	// 注册自定义校验方式
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		for sign, fun := range cvalidator.RegisterItems {
			errVa := v.RegisterValidation(sign, fun)
			if errVa != nil {
				panic(errVa.Error())
				os.Exit(0)
			}
		}
	}

	router.Use(middleware.Cors(), middleware.WriteLog())

	// 可以根据域名来确定哪一个
	routers.InitApiRouter(router)
	routers.InitAdminRouter(router)
	routers.InitPartnerRouter(router)

	router.Run("0.0.0.0:9090")

	return nil
}
